package keter.sec.springsec.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import keter.sec.springsec.model.MyUserDetails;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gkatzioura on 9/27/16.
 */
public class MyUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    	Record r = Db.findFirst("select id,username,password,status from org_user where username=?",username);
    	if(r==null){
            throw new UsernameNotFoundException("username not found");
    	}
    	if(r.getInt("status")==1){
            throw new LockedException("用户锁定!");
    	}
    	if(r.getInt("status")==2){
    		throw new DisabledException("用户禁用!");
    	}
        List<Record> roles = Db.find(
        	   "select r.name from org_role r ,org_user_role ur "
        	 + "where ur.user_id=? and ur.role_id=r.id"
               ,r.getInt("id")
        );
        UserDetails userDetails = new MyUserDetails(username,r.getStr("password"),getAuthoritiesFromRoles(roles));
        return userDetails;
    }
    
    private String[] getAuthoritiesFromRoles(List<Record> roles){
    	List<String> authorities = new ArrayList<String>(roles.size());
    	for (Record record : roles) {
    		authorities.add(record.getStr("name"));
		}
    	return authorities.toArray(new String[authorities.size()]);
    }

}
